/*LICENSE_BEGIN
 * ******************************************************************
 * All original parts of SoccerScope2003 have copyright (2003) by
 * Team YowAI, represented by Mr. Shuhei Shiota
 * The Department of Creative Informatics
 * The Graduate School of Information Science and Technology
 * The University of Tokyo
 * 
 * Additional classes (except libraries in /lib) were developed by 
 * the Dainamite Robocup-Team of the DAI-Labor, TU-Berlin 
 * (www.dai-labor.de)
 * 
 * Extended/new classes/packages are:
 *   soccerscope.analyzer.LogfileAnalyzer
 *   soccerscope.daistatistic.*
 *   soccerscope.daistatistic.charts.*
 *   soccerscope.daistatistic.tools.*
 *   soccerscope.db.*
 *   soccerscope.dialog.*
 *   soccerscope.model.PlayerWorldModel
 *   soccerscope.model.SimplePlayer
 *   soccerscope.net.AgentConnector
 *   soccerscope.training.*
 *   soccerscope.training.conditions.*
 * ******************************************************************
LICENSE_END*/
package soccerscope.util.analyze;

import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Iterator;

import soccerscope.model.ClientScene;
import soccerscope.model.GameEvent;
import soccerscope.model.PlayMode;
import soccerscope.util.geom.Point2f;

public class BallAverageAnalyzer extends SceneAnalyzer {

	public static String NAME = "Ball Ave";

	private ArrayList positionList;

	private double x;

	private double y;

	public BallAverageAnalyzer() {
		this.positionList = new ArrayList();
	}

	@Override
	public void init() {
		super.init();
		this.positionList = new ArrayList();
	}

	@Override
	public String getName() {
		return NAME;
	}

	@Override
	public Object getValueAt(int col, int fromTime, int toTime) {
		count(fromTime, toTime);
		NumberFormat nf = NumberFormat.getInstance();
		nf.setMaximumIntegerDigits(2);
		nf.setMaximumFractionDigits(2);
		switch (col) {
		case ROW_NAME:
			return getName();
		case LEFT:
			return nf.format(this.x) + ", " + nf.format(this.y);
		case RIGHT:
		default:
			return " ";
		}
	}

	@Override
	public void count(int fromTime, int toTime) {
		int count = 0;
		this.x = 0;
		this.y = 0;
		Iterator it = this.positionList.iterator();
		while (it.hasNext()) {
			Position p = (Position) it.next();
			if (fromTime <= p.time && p.time <= toTime) {
				count++;
				this.x += p.pos.x;
				this.y += p.pos.y;
			}
		}
		if (count != 0) {
			this.x /= count;
			this.y /= count;
		}
	}

	public class Position {
		public int time;

		public Point2f pos;

		Position(int time, Point2f pos) {
			this.time = time;
			this.pos = pos;
		}
	}

	@Override
	public GameEvent analyze(ClientScene clientScene, ClientScene prev) {
		if (clientScene.pmode.pmode != PlayMode.PM_PlayOn) {
			return null;
		}

		this.positionList.add(new Position(clientScene.time,
				clientScene.ball.pos));

		return null;
	}
}
